﻿using System.Threading;
using DM4;
using sscore;
using System;
using System.Collections.Generic;
using sscore.Utils;
using System.Text.RegularExpressions;
using System.IO;
using sscore.Requests;
using System.Net;

namespace GU
{
    public class GU : ModuleBase
    {       
        private readonly string _offenderLink;
        private readonly string _imageLink;
        private const string StateName = "GU";
        private ResultFile _imagesResultFile;
        private readonly List<string> _searchUrls;

        public GU()
        {
            //initialize main system constants
            ModuleCode = "SO_GU";
            Description = "GU Sex Offenders";
            Version = "1.0";

            RootUrl = "http://www.guamcourts.org/";
            _offenderLink = RootUrl + "sor/OffenderDetail.asp?OffenderId={0}.jpg";
            _imageLink = RootUrl + "sor/offImage/{0}.jpg";

            _searchUrls = new List<string> { 
                RootUrl + "sor/LevelResult.asp?Level=1&S_Level=Search+Level&offset={0}" ,
                RootUrl + "sor/LevelResult.asp?Level=2&S_Level=Search+Level&offset={0}", 
                RootUrl + "sor/LevelResult.asp?Level=3&S_Level=Search+Level&offset={0}",
                RootUrl + "sor/DOCResult.asp?offset={0}",
                RootUrl + "sor/OffIslandResult.asp?offset={0}",
                RootUrl + "sor/DeportedResult.asp?offset={0}"}; ;

            //for creating sessions
            StartParam = 0;
            StopParam = _searchUrls.Count - 1;

            //initialize help 
            AddToHelp(DM4Consts.StartPosition, String.Format("{0}...{1}", StartParam, StopParam));
            AddToHelp(DM4Consts.EndPositon, String.Format("{0}...{1}", StartParam, StopParam));

            AddToHelp(DM4Consts.IsDownload, "true|false");
            AddToHelp(DM4Consts.IsDownloadImg, "true|false");
            AddToHelp(DM4Consts.InsertToDb, "false|true", "(Expected: servername, dbname)");
            AddToHelp(DM4Consts.ServerName, "");
            AddToHelp(DM4Consts.DbName, "");
            AddToHelp(DM4Consts.IsClearDb, "false|true");
            AddToHelp(DM4Consts.TestParam, "false|true");         
        }

        private void SetParametersDefaults()
        {
            Params.CreateBooleanParam(DM4Consts.IsDownload, true);
            Params.CreateBooleanParam(DM4Consts.IsDownloadImg, true);
            Params.CreateBooleanParam(DM4Consts.InsertToDb, false);
            Params.CreateBooleanParam(DM4Consts.IsClearDb, false);
            Params.CreateStringParam(DM4Consts.DbName, "");
            Params.CreateStringParam(DM4Consts.ServerName, "");
            Params.CreateIntegerParam(DM4Consts.StartPosition, StartParam);
            Params.CreateIntegerParam(DM4Consts.LastPosition, Params.GetIntegerParam(DmConsts.StartPosition));
            Params.CreateIntegerParam(DM4Consts.EndPositon, StopParam);
            Params.CreateIntegerParam(DM4Consts.LastRecord, 0);
        }

        public override OperationResult Init(IDM4Core iCore, DmTaskParams param)
        {
            //use basic initialization sequence
            base.Init(iCore, param);

            SetParametersDefaults();
            return new OperationResult { Result = DM4Consts.Ok };
        }

        public override OperationResult Start()
        {
            DoWork();
            return new OperationResult { Result = DM4Consts.Ok };
        }

        public override OperationResult DoWork()
        {
            OperationResult or = new OperationResult { Result = DM4Consts.ErrorUnknown };

            if (!Ct.IsCancellationRequested)
            {
                WriteLog("Start parameters:", MessageType.Warning);
                foreach (KeyValuePair<string, string> kvp in Params.GetDictionary()) //get all existing parameters
                    WriteLog(String.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value), MessageType.Warning);

                if (Params.GetBooleanParam(DM4Consts.IsDownload))
                    Load();

                if (Params.GetBooleanParam(DM4Consts.InsertToDb))
                    if ((Params.GetStringParam(DM4Consts.DbName) == "") || (Params.GetStringParam(DM4Consts.ServerName) == ""))
                    {
                        or.Message = String.Format("{0} or {1} is empty", DM4Consts.DbName, DM4Consts.ServerName);
                        ResultCode = DM4Consts.SessionResultCodeError;
                        ResultMessage = or.Message;
                        UpdateStatus(DmConsts.Error);
                        WriteErrorLog(or.Message); //writting to error and session log   

                        return or;
                    }
                    else
                    {
                        //insert offenders to db 
                        UpdateStatus(DM4Consts.SessionInsertToDb);

                        Offenders.OffInsertToDatabase(StateName, Params.GetStringParam(DmConsts.DbName),
                             Params.GetStringParam(DmConsts.ServerName), ResultDir, Params.GetBooleanParam(DmConsts.IsClearDb),
                             WriteLog);

                    }

                //check if need abort task
                if (Ct.IsCancellationRequested)
                {
                    ResultCode = DM4Consts.SessionResultTerminateByUser;
                    ResultMessage = "Session terminated by user";
                    UpdateStatus(DM4Consts.SessionWait);
                    WriteLog("Session aborted by user", MessageType.Cool);
                }
                else
                {
                    UpdateProgress(1);
                    ResultCode = DM4Consts.SessionResultCodeOk;
                    ResultMessage = String.Format("Session complete, errors : {0}, records : {1}", TaskParams.ErrorCount, TaskParams.RecordCount);
                    UpdateStatus(DM4Consts.SessionComplete);
                    WriteLog("------------Finish----------------", MessageType.Cool);
                }
            }
            else
            {
                ResultCode = DM4Consts.SessionResultTerminateByUser;
                ResultMessage = "Session terminated by user";
                UpdateStatus(DM4Consts.SessionWait);
                WriteLog("Session aborted by user", MessageType.Cool);
            }


            return or;
        }

        private void Load()
        {
            string resultFileName = String.Format("{0}\\{1}.{2}", ResultDir, TaskParams.SessionId, DmConsts.ResultFilesExtension);
            bool workFlag = true;

            ResultFile = new ResultFile(resultFileName, OffendersResult.GetHeader());
            _imagesResultFile = new ResultFile(String.Format("{0}\\{1}_images.{2}", ResultDir, TaskParams.SessionId, DM4Consts.ResultFilesExtension), "FileName|FileUrl");
            try
            {
                while (workFlag)
                {
                    //рабочий цикл
                    string error;

                    try
                    {
                        error = "";  //Required!!  /*if (!String.IsNullOrEmpty(error)) --> restart thread; else --> download finished*/

                        WriteLog("Start download...");
                        Searching();
                    }
                    catch (Exception e)
                    {
                        error = e.Message;
                    }

                    if (!String.IsNullOrEmpty(error))
                    {
                        Thread.Sleep(30000);
                        WriteErrorLog(error);
                        WriteLog("Try continue work...", MessageType.Warning);
                    }
                    else
                    {
                        workFlag = false;  //все нормально откачало, заканчиваем работу
                    }
                }
            }
            finally
            {
                ResultFile.Close();
                _imagesResultFile.Close();
            }
        }

        private void Searching()
        {
            if (Test)
            {
                Params.SetIntegerParam(DmConsts.LastPosition, Params.GetIntegerParam(DmConsts.StartPosition));
                Params.SetIntegerParam(DmConsts.EndPositon, Params.GetIntegerParam(DmConsts.StartPosition));
            }

            if (Params.GetIntegerParam(DmConsts.EndPositon) > StopParam)
                Params.SetIntegerParam(DmConsts.EndPositon, StopParam);

            for (int indSearchParam = Params.GetIntegerParam(DmConsts.LastPosition); indSearchParam <= Params.GetIntegerParam(DmConsts.EndPositon); indSearchParam++)
            {
                //check if need abort task
                if (Ct.IsCancellationRequested)
                    break;

                Params.SetIntegerParam(DmConsts.LastPosition, indSearchParam);
                UpdateProgress();

                do
                {
                    if (Ct.IsCancellationRequested)
                        break;

                    string url = string.Format(_searchUrls[Params.GetIntegerParam(DmConsts.LastPosition)], Params.GetIntegerParam(DmConsts.LastRecord));

                    WriteLog(String.Format("start processing list [{0}][{1}]; offender [{2}] ", url,
                        Params.GetIntegerParam(DmConsts.LastPosition),
                        Params.GetIntegerParam(DmConsts.LastRecord)));

                    string html = GetRequest.UrlOnly(url, Rpm);
                    ParseResultPage(html);

                    if (!RegExpr.IsMatch(html, @"(?si:>\s*Next\s*</a>)")) 
                        break;
                }
                while (true);

                Params.SetIntegerParam(DmConsts.LastRecord, 0);
            }
        }

        private void ParseResultPage(string html)
        {
            html = HtmlUtils.KillSpace(HtmlUtils.ReplaceSpecSymbols(html.Replace("\r\n", " ").Replace("\t", " ").Replace("\r", " ").Replace("\n", " ")));

            if (!RegExpr.IsMatch(html, @"(?si:Designed by the Judiciary of Guam)"))
                throw new Exception(String.Format("Result page: {0}{1}{2}", DmConsts.ExcNeedRestart, Environment.NewLine, html));

            MatchCollection mc = RegExpr.ParseMatchCollection(html, @"(?si:offImage/([\S]+).jpg)");
            WriteLog(String.Format("found [{0}] matches", mc.Count));
            if (mc.Count == 0)
                throw new Exception(DmConsts.ExcNeedRestart + Environment.NewLine + html);

            foreach (Match matchLoc in mc)
            {
                //check if need abort task
                if (Ct.IsCancellationRequested)
                    break;
                
                string lookupKey = matchLoc.Groups[1].Value;
                string url = string.Format(_offenderLink, lookupKey);
                WriteLog(String.Format("Navigate to offender [{0}][{1}]", Params.GetIntegerParam(DmConsts.LastRecord), url));
                string offenderHtml = GetRequest.WithCookies(url, Rpm);
                              
                if (string.IsNullOrEmpty(offenderHtml) && Rpm.LastException != null
                  && Rpm.LastException.Message.Contains("(500)"))
                {
                    WriteLog(String.Format("Error 500 for offenders page: [{0}]", url));
                }
                else if (!string.IsNullOrEmpty(offenderHtml) && RegExpr.IsMatch(html, @"(?si:Designed by the Judiciary of Guam)"))
                {
                    WriteLog(String.Format("ParseOffender [{0}][{1}]", Params.GetIntegerParam(DmConsts.LastRecord), lookupKey));
                    ParseOffender(offenderHtml, lookupKey);
                    UpdateRecordCount(1);
                }
                else 
                    throw new Exception("Offender page: " + DmConsts.ExcNeedRestart);

                Params.SetIntegerParam(DmConsts.LastRecord, Params.GetIntegerParam(DmConsts.LastRecord) + 1);
            }
        }

        private void ParseOffender(string offenderHtml, string lookupKey)
        {
            offenderHtml = HtmlUtils.KillSpace(HtmlUtils.ReplaceSpecSymbols(offenderHtml.Replace("\r\n", " ").Replace("\t", " ").Replace("\r", " ").Replace("\n", " ")));
            using (OffendersResult or = new OffendersResult())
            {
                or.Source_State = StateName;
                or.offenderLink = string.Format(_offenderLink, lookupKey);
                or.Source_id = lookupKey;

                or.fullname = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Full Name\s*:\s*</div>\s*</td>\s*<td[^<>]*?><div[^<>]*?>([^<>]*?)</div>)").Trim();
                or.Status = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Offender Status\s*:\s*</div>\s*</td>\s*<td[^<>]*?><div[^<>]*?>([^<>]*?)</div>)").Trim();
                or.Risk = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Level\s*:\s*</div>\s*</td>\s*<td[^<>]*?><div[^<>]*?>([^<>]*?)</div>)").Trim();
                or.Birthdate = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Date of Birth\s*:\s*</div>\s*</td>\s*<td[^<>]*?><div[^<>]*?>([^<>]*?)</div>)").Trim();
                or.Ethnicity = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Ethnicity\s*:\s*</div>\s*</td>\s*<td[^<>]*?><div[^<>]*?>([^<>]*?)</div>)").Trim();
                or.sex = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Gender\s*:\s*</div>\s*</td>\s*<td[^<>]*?><[^<>]*?>([^<>]*?)<)").Trim();
                or.height = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Height\s*:\s*</div>\s*</td>\s*<td[^<>]*?><div[^<>]*?>([^<>]*?)</div>)").Trim();
                or.weight = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Weight\s*:\s*</div>\s*</td>\s*<td[^<>]*?><div[^<>]*?>([^<>]*?)</div>)").Trim();
                or.hair_color = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Hair Color\s*:\s*</div>\s*</td>\s*<td[^<>]*?><div[^<>]*?>([^<>]*?)</div>)").Trim();
                or.eye_color = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Eye Color\s*:\s*</div>\s*</td>\s*<td[^<>]*?><div[^<>]*?>([^<>]*?)</div>)").Trim();

                or.Birth_place =  String.Format("{0}@{1}", 
                    RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Birth Place\s*:\s*</div>\s*</td>\s*<td[^<>]*?><div[^<>]*?>([^<>]*?)</div>)").Trim(), 
                    RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Birth State\s*:\s*</div>\s*</td>\s*<td[^<>]*?><div[^<>]*?>([^<>]*?)</div>)").Trim());

                if (or.Birth_place == "@") or.Birth_place = "";


                string str = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Occured In\s*:\s*</div>(.*?)<br[^<>]*?>\s*<br[^<>]*?>)").Trim();
                MatchCollection mc = RegExpr.ParseMatchCollection(str, 
                    @"(?si:<tr[^<>]*?>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?</tr>)");
                foreach (Match m in mc)
                {
                    or.Crime += m.Groups[1].Value.Trim() + ";";
                    or.Crime += m.Groups[2].Value.Trim() + ";";
                    or.Crime += m.Groups[3].Value.Trim() + ";";
                    or.Crime += m.Groups[4].Value.Trim() + "~";
                }
                if (!string.IsNullOrEmpty(or.Crime))
                    or.Crime = "Offense;Conviction Date;Occured;Count~" + or.Crime;

                //scar
                str = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Scar Description\s*:\s*</div>(.*?)<br[^<>]*?>\s*<br[^<>]*?>)").Trim();
                mc = RegExpr.ParseMatchCollection(str, @"(?si:<tr[^<>]*?>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?</tr>)");
                foreach (Match m in mc)
                {
                    or.marks += m.Groups[1].Value.Trim() + ";";
                    or.marks += m.Groups[2].Value.Trim() + "~";
                }
                //marks
                str = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Mark Description\s*:\s*</div>(.*?)<br[^<>]*?>\s*<br[^<>]*?>)").Trim();
                mc = RegExpr.ParseMatchCollection(str, @"(?si:<tr[^<>]*?>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?</tr>)");
                foreach (Match m in mc)
                {
                    or.marks += m.Groups[1].Value.Trim() + ";";
                    or.marks += m.Groups[2].Value.Trim() + "~";
                }
                //tattoo
                str = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Tattoo Description\s*:\s*</div>(.*?)<br[^<>]*?>\s*<br[^<>]*?>)").Trim();
                mc = RegExpr.ParseMatchCollection(str, @"(?si:<tr[^<>]*?>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?</tr>)");
                foreach (Match m in mc)
                {
                    or.marks += m.Groups[1].Value.Trim() + ";";
                    or.marks += m.Groups[2].Value.Trim() + "~";
                }

                if (!string.IsNullOrEmpty(or.marks))
                    or.marks = "Location;Description~" + or.marks;

                str = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Address\s*:\s*</div>(.*?)<br[^<>]*?>\s*<br[^<>]*?>)").Trim();
                mc = RegExpr.ParseMatchCollection(str, 
                    @"(?si:<tr[^<>]*?>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?</tr>)");
                foreach (Match m in mc)
                {
                    or.Address = m.Groups[1].Value.Trim();
                    or.City = m.Groups[2].Value.Trim();
                    or.State = m.Groups[3].Value.Trim();
                    or.Zip = m.Groups[4].Value.Trim();
                }

                str = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Employment\s*:\s*</div>(.*?)<br[^<>]*?>\s*<br[^<>]*?>)").Trim();
                mc = RegExpr.ParseMatchCollection(str, @"(?si:<tr[^<>]*?>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?</tr>)");
                foreach (Match m in mc)
                {
                    or.Employer = m.Groups[1].Value.Trim();
                }


                str = RegExpr.Parse(offenderHtml, @"(?si:<div[^<>]*?>\s*Additional Details\s*:\s*</div>(.*?)<p[^<>]*?>\s*</p>)").Trim();
                mc = RegExpr.ParseMatchCollection(str, 
                    @"(?si:<tr[^<>]*?>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?<div[^<>]*?>([^<>]*?)</div>.*?</tr>)");
                foreach (Match m in mc)
                {
                    or.Vehicle += m.Groups[1].Value.Trim() + ";";
                    or.Vehicle += m.Groups[2].Value.Trim() + ";";
                    or.Vehicle += m.Groups[3].Value.Trim() + ";";
                    or.Vehicle += m.Groups[4].Value.Trim() + ";";
                    or.Vehicle += m.Groups[5].Value.Trim() + ";";
                    or.Vehicle += m.Groups[6].Value.Trim() + "~";
                }
                if (!string.IsNullOrEmpty(or.Vehicle))
                    or.Vehicle = "Make;Style;Color;Year;Number;Details~" + or.Vehicle;


                if (Params.GetBooleanParam(DmConsts.IsDownloadImg))
                {
                    or.Image_ID = Guid.NewGuid() + ".jpg";
                    or.ImageLink = string.Format(_imageLink, or.Source_id);
                    try
                    {
                        Offenders.DownloadImageWithExceptions(_imagesResultFile, String.Format("{0}\\{1}\\{2}", ResultDir, DmConsts.PhotosDir, or.Image_ID), 
                            or.ImageLink, TaskParams.SessionId);
                    }
                    catch (WebException ex)
                    {
                        if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
                        {
                            or.Image_ID = "";
                            or.ImageLink = "";
                        }
                        else throw new Exception(DmConsts.ExcInvalidLoadingImage, ex);
                    }
                }

                if (or.Image_ID != "" && !File.Exists(String.Format("{0}\\{1}\\{2}", ResultDir, DmConsts.PhotosDir, or.Image_ID)))
                    throw new Exception(DmConsts.ExcImgNotFound);

                ResultFile.Write(or.GetValues());
            }
        }

        private void UpdateProgress()
        {
            if (Params.GetIntegerParam(DmConsts.StartPosition) > Params.GetIntegerParam(DmConsts.EndPositon))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.StartPosition), Params.GetIntegerParam(DmConsts.EndPositon),
                    DmConsts.StartPosition, DmConsts.EndPositon));
            if (Params.GetIntegerParam(DmConsts.LastPosition) > Params.GetIntegerParam(DmConsts.EndPositon))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.LastPosition), Params.GetIntegerParam(DmConsts.EndPositon),
                    DmConsts.StartPosition, DmConsts.EndPositon));
            if (Params.GetIntegerParam(DmConsts.StartPosition) > Params.GetIntegerParam(DmConsts.LastPosition))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.StartPosition), Params.GetIntegerParam(DmConsts.LastPosition),
                    DmConsts.StartPosition, DmConsts.LastPosition));
            UpdateProgress(((double)(Params.GetIntegerParam(DmConsts.LastPosition) - Params.GetIntegerParam(DmConsts.StartPosition))) / (Params.GetIntegerParam(DmConsts.EndPositon) - Params.GetIntegerParam(DmConsts.StartPosition) + 1));
        }
    }
}
